package org.mybatis.generator.extend.servicegenerator;

import org.mybatis.generator.api.dom.java.*;

import java.util.Set;
import java.util.TreeSet;


/**
 * service实现 insert方法内容构造
 *
 * @author tangdelong
 * 2015年5月22日
 */
public class InsertMethodOfServiceGenerator extends AbstractJavaServiceMethodGenerator {

    boolean isSimple;

    public InsertMethodOfServiceGenerator(boolean isSimple) {
        super();
        this.isSimple = isSimple;
    }
    
    
    /**
     * 方法内容
     */
    public void addServiceElements(TopLevelClass topLevelClass){
    	Set<FullyQualifiedJavaType> importedTypes = new TreeSet<FullyQualifiedJavaType>();
       
    	FullyQualifiedJavaType mapper = new FullyQualifiedJavaType(introspectedTable.getMyBatis3JavaMapperType());
        FullyQualifiedJavaType parameterType;
        if (isSimple) {
            parameterType = new FullyQualifiedJavaType(introspectedTable.getBaseRecordType());
        } else {
            parameterType = introspectedTable.getRules().calculateAllFieldsClass();
        }

        importedTypes.add(parameterType);
        
        Method method = new Method();
        //method.addAnnotation("@Transactional");
        method.setReturnType(FullyQualifiedJavaType.getIntInstance());
        method.setVisibility(JavaVisibility.PUBLIC);
        method.setName(introspectedTable.getInsertSelectiveStatementId());
        method.addParameter(new Parameter(parameterType, "record")); //$NON-NLS-1$
        method.addAnnotation("@Override");
        StringBuffer sb = new StringBuffer();
        sb.append("return ");
        String shortName = mapper.getShortName();
        shortName = shortName.substring(0, 1).toLowerCase() + shortName.substring(1);
        sb.append(shortName + "."+introspectedTable.getInsertSelectiveStatementId()+"(record);");
        method.addBodyLine(sb.toString());
        method.addJavaDocLine("/** 增加，返回影响的行数 */");
        context.getCommentGenerator().addGeneralMethodComment(method, introspectedTable);

        if (context.getPlugins().clientInsertMethodGenerated(method, topLevelClass,
                introspectedTable)) {
        	topLevelClass.addImportedTypes(importedTypes);
        	topLevelClass.addMethod(method);
        }
    }


    public void addMapperAnnotations(Interface interfaze, Method method) {
        return;
    }
}